Uppdaterad
AJAX
Lägen för readyState
- UNSENT
- OPENED
- HEADERS_RECEIVED
- LOADING
- DONE
UNSENT
0: request not initialized
OPENED
1: server connection established
2: request received
LOADING
3: processing request
DONE
4: request finished and response is ready
onabort
onerror
onload
onloadend
onloadstart
onprogress
onreadystatechange
ontimeout
readyState
(onreadystatechange
)
status
statusText
response
progress
(onprogress
)
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
xhr = new XMLHttpRequest();
xhr.onloadend = function() {
alert(JSON.parse(xhr.response).query[0].title);
};
xhr.open('GET', '/folder/file.extension?query=1&q=2', true);
xhr.send();
xhr.withCredentials = true;
Lägg till header för att undvika problem med CORS
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('custom-header', 'value');
function smart_split(cntn, first, second) {
arr = cntn.split(first);
obj = {};
arr.forEach(function (line) {
parts = line.split(second);
header = parts.shift();
value = parts.join(second);
obj[header] = value;
});
return obj;
}
xhr = new XMLHttpRequest();
xhr.open('GET', window.location, true);
xhr.onloadend = function() {
headers = smart_split(xhr.getAllResponseHeaders().trim(), /[\r\n]+/, ': ');
type = smart_split('mime-type=' + headers['content-type'], '; ', '=');
}
xhr.send();
xhr = new XMLHttpRequest();
xhr.setRequestHeader('custom-header', 'value');
xhr.open('GET', '/folder/file.extension?query=1&q=2', true);
xhr.onloadend = function() {
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr.getAllResponseHeaders());
}
xhr.send();
Räkna ut hur många procent som är kvar med JavaScript
xhr.onprogress = function(event) {
if (event.lengthComputable) {
percentComplete = event.loaded / event.total * 100;
}
}
formData = new FormData();
formData.append('key', value);
xhr.send(formData);
$.ajax({
url: "/file.php",
data: {
'q' : ''
}, success: function(msg) {
console.log('Ett bra uppstod: ' + msg);
}, error: function(msg) {
console.log('Ett fel uppstod: ' + msg);
}
});
xhr = new XMLHttpRequest();
xhr.open('HEAD', window.location, true);
xhr.send();
xhr.addEventListener('readystatechange', processRequest, false);
function processRequest(e) {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 304) {
alert('🛜');
} else {
alert('✈️');
}
}
}
Testa här